<template>
  <view class="publish-container">
    <go-back></go-back>

    <view class="header">
      <text class="header-title">发布笔记</text>
    </view>

    <view class="form-container">
      <!-- 标题输入区域 -->
      <view class="title-area">
        <input
          class="title-input"
          v-model="formData.article_title"
          placeholder="请输入标题..."
          maxlength="20"
        />
        <text class="input-count">{{ formData.article_title.length }}/20</text>
      </view>
      <!-- 内容输入区域 -->
      <view class="content-area">
        <textarea
          class="content-textarea"
          v-model="formData.article_content"
          placeholder="分享你的新鲜事..."
          maxlength="1000"
          auto-height
        />
        <text class="input-count"
          >{{ formData.article_content.length }}/1000</text
        >
      </view>

      <!-- 图片上传 -->
      <view class="image-upload-area">
        <uni-file-picker
          v-model="article_images"
          fileMediatype="image"
          mode="grid"
          :limit="9"
          @select="selectImage"
          @delete="deletedImageList"
        />
      </view>

      <!-- 功能区域 -->
      <view class="function-area">
        <!-- 标签选择 -->
        <view class="tags-section">
          <view class="tags-header">
            <uni-icons type="tag" size="20" color="#999"></uni-icons>
            <text class="tags-title">选择标签</text>
          </view>
          <view class="tags-container">
            <view
              v-for="(tag, index) in tags"
              :key="index"
              class="tag-item"
              :class="{
                active: formData.category_id === tag.category_id,
              }"
              @click="toggleTag(tag)"
            >
              # {{ tag.category_name }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="publish-btn" @click="submitForm">发布</view>
  </view>
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import { getCategory, addArticle, deletedImage } from "../../api/campus";

  const article_images = ref([]); // 图片文件列表
  const formData = ref({
    article_title: "",
    article_content: "",
    category_id: null,
  });

  const tags = ref([]);

  const getCategoryList = async () => {
    try {
      const res = await getCategory();
      tags.value = res.data.filter((_, index) => index != 0);
    } catch (error) {
      uni.showToast({
        title: "获取分类失败",
        icon: "error",
      });
    }
  };
  const toggleTag = (tag) => {
    formData.value.category_id =
      formData.value.category_id === tag.category_id ? null : tag.category_id;
  };

  const selectImage = async (e) => {
    if (!e.tempFiles?.length) {
      uni.showToast({ title: "请选择图片", icon: "none" });
      return;
    }
    const uploadResults = [];

    for (const file of e.tempFiles) {
      const res = await uni.uploadFile({
        url: "http://localhost:8000/index/campus/uploadImage",
        filePath: file.path,
        name: "file",
        formData: { filename: file.name },
      });

      const data = JSON.parse(res.data);
      if (data.code === 200) {
        uploadResults.push(data.data[0]);
        article_images.value.push(data.data[0]);
        console.log(article_images.value);
      } else {
        throw new Error(data.msg || "上传失败");
      }
    }
  };
  const deletedImageList = async (e) => {
    const imageToDelete = article_images.value[e.index];
    console.log(imageToDelete);

    const res = await deletedImage(imageToDelete);
    if (res.code === 200) {
      article_images.value = article_images.value.filter(
        (_, index) => index !== e.index
      );
      uni.showToast({ title: "删除成功", icon: "success" });
    } else {
      throw new Error(res.msg || "删除失败");
    }
  };

  const submitForm = async () => {
    try {
      if (!formData.value.article_title.trim()) {
        uni.showToast({ title: "请输入标题", icon: "error" });
        return;
      }
      if (!formData.value.article_content.trim()) {
        uni.showToast({ title: "请输入内容", icon: "error" });
        return;
      }
      if (!formData.value.category_id) {
        uni.showToast({ title: "请选择分类标签", icon: "error" });
        return;
      }
      // if (article_images.value.length == 0) {
      //   uni.showToast({ title: "请至少上传一张图片", icon: "error" });
      //   return;
      // }

      const form = {
        ...formData.value,
        article_images: article_images.value,
      };

      const res = await addArticle(form);
      if (res.code === 200) {
        uni.showToast({ title: "发布成功", icon: "success" });
        formData.value = {
          article_title: "",
          article_content: "",
          category_id: null,
        };
        article_images.value = [];
        uni.navigateBack();
      }
    } catch (error) {
      uni.showToast({ title: error.message || "发布失败", icon: "error" });
    }
  };

  onMounted(() => {
    getCategoryList();
  });
</script>

<style lang="scss">
  .publish-container {
    min-height: 100vh;
    background-color: #ffffff;
    position: relative;

    .header {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      background-color: #ffffff;
      position: sticky;
      top: 80rpx;
      z-index: 100;
      border-bottom: 1px solid #f5f5f5;
      .back-button {
        position: absolute;
        top: 15rpx;
        left: 20rpx;
        z-index: 300;
        margin-right: 20rpx;
      }

      .header-title {
        flex: 1;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        text-align: center;
      }
    }

    .form-container {
      padding: 20rpx;
      margin-top: 100rpx;
      .title-area {
        padding: 20rpx;
        position: relative;
        margin-bottom: 30rpx;
        border-bottom: 3px solid #eee;
        box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.05);

        .title-input {
          width: 100%;
          font-size: 32rpx;
          line-height: 1.5;
          padding: 0;
          box-sizing: border-box;
          outline: none;
          border: none;
          color: #333;
        }

        .input-count {
          position: absolute;
          right: 20rpx;
          bottom: 20rpx;
          font-size: 24rpx;
          color: #999;
          opacity: 0.8;
        }
      }
      .content-area {
        padding: 20rpx;
        position: relative;
        margin-bottom: 30rpx;
        box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.05);

        .content-textarea {
          width: 100%;
          min-height: 200rpx;
          font-size: 30rpx;
          line-height: 1.5;
          padding: 0;
          box-sizing: border-box;
          outline: none;
          border: none;
          color: #333;
        }

        .input-count {
          position: absolute;
          right: 20rpx;
          bottom: 0;
          font-size: 24rpx;
          color: #999;
          opacity: 0.8;
        }
      }

      .image-upload-area {
        margin-bottom: 30rpx;
      }

      .function-area {
        padding: 20rpx 0;
        border-top: 1px solid #f5f5f5;

        .tags-section {
          padding: 20rpx 0;

          .tags-header {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;

            .tags-title {
              margin-left: 10rpx;
              font-size: 28rpx;
              color: #666;
            }
          }

          .tags-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20rpx;

            .tag-item {
              padding: 10rpx 20rpx;
              background-color: #f5f5f5;
              border-radius: 30rpx;
              font-size: 26rpx;
              color: #666;

              &.active {
                background-color: rgba(255, 36, 66, 0.1);
                color: #ff2442;
              }
            }
          }
        }
      }
    }
    .publish-btn {
      position: absolute;
      bottom: 300rpx;
      left: 50%;
      transform: translateX(-50%);
      height: 60rpx;
      padding: 10rpx 30rpx;
      width: 150rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      letter-spacing: 10rpx;
      background-color: #ff2442;
      color: #ffffff;
      border-radius: 30rpx;
      font-size: 32rpx;
      font-weight: 600;
    }
  }
</style>
